package com.gree.flowable.app.services.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gree.flowable.app.mapper.*;
import com.gree.flowable.app.mapper.dao.FormDataDao;
import com.gree.flowable.app.mapper.plus.FormBusinessInfoService;
import com.gree.flowable.app.pojo.form.FormBusinessInfo;
import com.gree.flowable.app.pojo.form.FormModel;
import com.gree.flowable.app.pojo.vo.ReturnVO;
import com.gree.flowable.app.services.IFormDataService;
import com.gree.flowable.app.tools.constants.ReturnCode;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author ：180849
 * @date ：Created in 2021/4/6 9:10
 * @description：表单数据实现层
 * @modified By：
 * @version: 1.0
 */
@Service
public class IFormDataServiceImpl implements IFormDataService {

    @Autowired
    private FormDataMapper formDataMapper;

    @Autowired
    private FormDataDao formDataDao;

    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private FormModelMapper formModelMapper;

    @Autowired
    private FlwFormNodesetMapper flwFormNodesetMapper;

    @Autowired
    private FormBusinessMapper formBusinessMapper;

    @Autowired
    private FormBusinessInfoMapper formBusinessInfoMapper;

    @Autowired
    private FormBusinessInfoService formBusinessInfoService;

    /**
     * 添加表单数据
     *
     * @param businessKey     流程实例id
     * @param formId   表单id
     * @param data 表单数据
     * @return 添加的条数
     */
    @Override
    public ReturnVO addFormData(String businessKey, String formId, Map<String,Object> data) {

        ReturnVO<Integer> result = null;
       /* TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        try {
            //进行数据插入
            formDataDao.addFormData(businessKey, formId, data);
            //查询数据，确定是否插入成功
            Integer resultTotal = formDataMapper.queryFormData(businessKey, formId);
            dataSourceTransactionManager.commit(transactionStatus);
            if (resultTotal == 1){
                result = new ReturnVO<>(ReturnCode.SUCCESS,"数据添加成功",resultTotal);
            } else {
                result = new ReturnVO<>(ReturnCode.FAIL,"数据添加失败",resultTotal);
            }
        } catch (Exception e) {
            e.printStackTrace();
            dataSourceTransactionManager.rollback(transactionStatus);
            result = new ReturnVO<>(ReturnCode.FAIL,"数据添加失败，原因为："+e.getMessage());
        }*/
        for (String key : data.keySet()) {
            //判断是否为上传文件的组件
            QueryWrapper<FormModel> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(FormModel::getFormId,formId).eq(FormModel::getFields,key);
            FormModel formModel = formModelMapper.selectOne(queryWrapper);
            //如果为上传文件的组件，将String转为List
            if ("upload-file".equals(formModel.getShape())){
                String uploadInfo = JSONObject.toJSONString(data.get(key));
                data.put(key,uploadInfo);
            }
            //如果为多选框，将ArrayList转为String做数据存储
            if ("checkbox".equals(formModel.getShape())){
                String checkBoxInfo =  JSONObject.toJSONString(data.get(key));
                data.put(key,checkBoxInfo);
            }
        }
        Integer resultTotal = formDataMapper.addFormData(businessKey, formId, data);
        if (resultTotal > 0){
            result = new ReturnVO<>(ReturnCode.SUCCESS,"数据添加成功",resultTotal);
        } else {
            result = new ReturnVO<>(ReturnCode.FAIL,"数据添加失败",resultTotal);
        }


//        List<FormData> formDataList = new LinkedList<>();
//        for (String key :data.keySet()) {
//            FormData formData = new FormData();
//            formData.setPrid(businessKey);
//            formData.setFormId(formId);
//            formData.setFields(key);
//            String value = data.get(key).toString();
//            formData.setValue(value);
//            formDataList.add(formData);
//        }
//
//        boolean saveBatch = formDataService.saveBatch(formDataList);
////        Integer addFormDataTotal = formDataMapper.addFormData(formDataList);
//        if (saveBatch){
//            result = new ReturnVO(ReturnCode.SUCCESS,"数据插入成功",1);
//        } else {
//            result = new ReturnVO(ReturnCode.FAIL,"数据插入失败",0);
//        }
        return result;
    }

    /**
     * 修改表单数据
     *
     * @param businessKey   流程实例id
     * @param formId 表单id
     * @param data   表单数据
     * @return 修改的条数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnVO updateFormData(String businessKey, String formId, Map<String, Object> data) {
        List<FormBusinessInfo> formBusinessInfoList = new LinkedList<>();
        for (String key : data.keySet()) {
            //判断是否为上传文件的组件
            QueryWrapper<FormModel> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(FormModel::getFormId,formId).eq(FormModel::getFields,key);
            FormModel formModel = formModelMapper.selectOne(queryWrapper);
            //如果为上传文件的组件，将String转为List
            if (!"business_key".equals(key) &&"upload-file".equals(formModel.getShape())){
                String uploadInfo = JSONObject.toJSONString(data.get(key));
                data.put(key,uploadInfo);
            }
            //如果为多选框，将ArrayList转为String做数据存储
            if (!"business_key".equals(key) &&"checkbox".equals(formModel.getShape())){
                String checkBoxInfo =  JSONObject.toJSONString(data.get(key));
                data.put(key,checkBoxInfo);
            }
            //修改表单信息
            String fieldType = formModel.getFieldType();
            FormBusinessInfo formBusinessInfo = new FormBusinessInfo();
            formBusinessInfo.setBusinessKey(businessKey);
            formBusinessInfo.setFields(key);
            formBusinessInfo.setFieldType(formModel.getFieldType());
            switch (fieldType){
                case "Date":
                case "Time":
                    formBusinessInfo.setLvaldate(Long.valueOf(data.get(key).toString()));
                    break;
                case "Integer":
                case "Double":
                    formBusinessInfo.setValnum(Double.valueOf((data.get(key)).toString()));
                    break;
                case "String":
                default:
                    formBusinessInfo.setValstr(/*JSONObject.toJSONString(data.get(key))*/data.get(key).toString());
            }
            formBusinessInfoList.add(formBusinessInfo);
        }



//        Execution execution = runtimeService.createExecutionQuery().processInstanceBusinessKey(businessKey).singleResult();
//        runtimeService.setVariables(execution.getId(), data);

//        boolean updateFormData = formBusinessInfoService.saveOrUpdateBatch(formBusinessInfoList);
        Integer info = formBusinessInfoMapper.updateFormBusinessInfo(formBusinessInfoList, businessKey);
//        Integer updateTotal = formDataMapper.updateFormData(businessKey, formId, data);
//        Integer delTotal = deleteFormData(businessKey, formId);
//        Integer deleteTotal = formDataMapper.deleteFormData(prid);
        ReturnVO result = null;
        if (info > 0){
            result = new ReturnVO(ReturnCode.SUCCESS,"更新成功",info);
        } else {
            result = new ReturnVO(ReturnCode.FAIL,"更新失败",info);
        }
        /*return addFormData(businessKey, formId, data);*/
        return result;
    }


    /**
     * 删除表单数据
     * @param businessKey      流程实例id
     * @param formId 表名
     * @return          删除的条数
     */
    @Override
    public Integer deleteFormData(String businessKey,String formId) {

        Integer deleteTotal = formDataMapper.deleteFormData(businessKey,formId);
        return deleteTotal;
    }

    /**
     * 查询表单数据
     * @param taskId     任务ID
     * @return          删除的条数
     */
    @Override
    public Map<String,Object> selectFormDataByBusinessKey(String taskId) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //根据taskID获取模型id
        String processDefinitionId = task.getProcessDefinitionId();
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();
        String processKey = processDefinition.getKey();
        String formId = flwFormNodesetMapper.getFormId(processKey);
        //根据taskID获取单号
        String processInstanceId = task.getProcessInstanceId();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        String businessKey = processInstance.getBusinessKey();
        Map<String, Object> dataMap = formDataMapper.quryData(businessKey, formId);
        return dataMap;
    }
}
